<?php

namespace app\unify\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use think\facade\Db;

class Installer extends Command
{

    protected function configure()
    {

        $this->setName('block')
            ->addArgument('block', Argument::OPTIONAL, "your block name")
            ->addArgument('action', Argument::OPTIONAL, "your action name")
            ->setDescription('Install Block');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln("-------执行开始-------");

        $block = trim($input->getArgument("block"));

        $dir1 = $this->app->getRootPath() . 'addon/' . $block;
        $dir2 = $this->app->getRootPath() . "vendor/" . $block;

        $dir = "";
        if(is_dir($dir1)){
            $dir = $dir1;
        }elseif(is_dir($dir2)){
            $dir = $dir2;
        }
        if(empty($dir)){
            $output->writeln("未找到该组件{$block}");
            return;
        }

        $db = Db::connect();

        $action = trim($input->getArgument('action'));
        switch ($action){
            case "install":
                $db->transaction(function () use ($output, $db, $dir) {
                    $installFile = $dir . "/src/sql/install.sql";
                    if(file_exists($installFile)){
                        $db->execute(file_get_contents($installFile));
                    }else{
                        $output->writeln("未找到文件：" . $installFile);
                    }

                    $demoFile = $dir . "/src/sql/demo.sql";
                    if(file_exists($demoFile)){
                        $db->execute(file_get_contents($demoFile));
                    }
                });
                break;
            case "uninstall":
                $db->transaction(function () use ($output, $db, $dir) {
                    $uninstallFile = $dir . "/src/sql/uninstall.sql";
                    if(file_exists($uninstallFile)){
                        $db->execute(file_get_contents($uninstallFile));
                    }else{
                        $output->writeln("未找到文件：" . $uninstallFile);
                    }
                });
                break;
            default:
                throw new \Exception("未定义[{$action}]操作");
        }
        $output->writeln("-------执行结束-------");
    }
}